package com.mp.approvalreq.servlet.comment;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.Comment;
import com.mp.approvalreq.service.ApprovalCommentServicePrx;
import com.mp.approvalreq.servlet.AbstractServlet;
import com.mp.comment.entity.File;
import com.mp.user.entity.User;
import com.mp.user.entity.dto.AttachmentDTO;
import com.mp.user.entity.po.Attachment;
import com.mp.user.service.AttachmentServicePrx;
import com.plusmoney.exception.ParameterException;
import com.plusmoney.util.DateTimeHelper;
import com.plusmoney.util.Utils;
import com.qq.tars.client.util.ServantUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 获取审批评论列表
 */
@WebServlet("/getCommentList")
public class GetCommentList extends AbstractServlet {

    private static final Logger logger = LoggerFactory.getLogger(GetCommentList.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        try {
            User user = getReqUser(req);

            String requestId = req.getParameter("requestId");
            String version = req.getParameter("version");
            check(requestId);
            Comment comment = initComment(requestId);

            ApprovalCommentServicePrx commentServicePrx = ServantUtils.getObject(ApprovalCommentServicePrx.class);
            List<Comment> commentList = commentServicePrx.getRequestCommentList(comment.getRequestId(), user.getCompanyInfoId());
            if (Utils.isNotEmpty(commentList)) {
                setCommentInfoAndCancelMsg(commentList, user);
                setCommentFileInfo(commentList, comment.getRequestId(), version);

                adjustOldData(commentList);
            }

            returnResponse(resp, commentList);
        } catch (Throwable e) {
            onThrowable(req, resp, e);
        }
    }

    private void returnResponse(HttpServletResponse resp, Object object) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("erpCode", "000");
        jsonObject.put("erpMsg", "获得成功");
        jsonObject.put("item", object);

        logger.info(jsonObject.toJSONString());

        printJson(resp, jsonObject.toJSONString());
    }

    private void adjustOldData(List<Comment> commentList) {
        for (Comment comment : commentList) {
            if (comment.getType() == 1) {
                if (StringUtils.isEmpty(comment.getFileCode())) {
                    comment.setFileCode(comment.getMsg());
                }
                comment.setMsg(null);
            }
        }
    }

    private void check(String requestId) {
        if (StringUtils.isEmpty(requestId)) {
            throw new ParameterException("审批ID不能为空");
        }
    }


    private Comment initComment(String requestId) {
        Comment comment = new Comment();
        comment.setRequestId(Integer.parseInt(requestId));
        return comment;
    }

    /**
     * @param comments
     * @param requestId
     * @param version
     * @throws Throwable
     */
    private void setCommentFileInfo(List<Comment> comments, int requestId, String version) throws Throwable {
        if (Utils.isEmpty(comments)) {
            return;
        }
        List<String> fileInfoList = new ArrayList<>();
        for (Comment comment : comments) {
            if (comment.getType() == 2 && comment.getIsCancel() == 0) {
                //  type=2: 需求更改加上去的,只有将type和attach置为0,前端才会显示Msg
                if (StringUtils.isEmpty(version)) {
                    comment.setMsg("评论包含文件，请更新大管加版本");
                    comment.setType(0);
                    comment.setFileName(null);
                } else {
                    fileInfoList.add(comment.getFileName());
                }
            }
        }

        if (Utils.isNotEmpty(fileInfoList)) {
            AttachmentServicePrx attachmentService = ServantUtils.getObject(AttachmentServicePrx.class);
            List<AttachmentDTO> list = attachmentService.getAttachmentList(String.valueOf(requestId), Attachment.APPROVAL_FILE);
            for (AttachmentDTO attachmentDTO : list) {
                for (Comment comment : comments) {
                    if (comment.getIsCancel() == 0) {
                        if (Objects.equals(attachmentDTO.getFileName(), comment.getFileName())) {
                            File file = new File();
                            file.setFileName(attachmentDTO.getFileName());
                            file.setOriginFileName(attachmentDTO.getOriginFileName());
                            file.setFileSuffix(attachmentDTO.getFileSuffix());
                            file.setFileSize(attachmentDTO.getFileSize());
                            comment.setFile(file);
                        }
                    }
                }
            }
        }
    }


    /**
     * 设置评论人信息和撤回消息
     *
     * @param comments
     * @param curUser
     */
    private void setCommentInfoAndCancelMsg(List<Comment> comments, User curUser) {

        List<Integer> crtIds = comments.stream().map(Comment::getCreateId).collect(Collectors.toList());

        if (Utils.isNotEmpty(crtIds)) {
            Date now = new Date();
            for (Comment comment : comments) {
                if (comment.getIsCancel() == 1) {
                    try {
                        if (Objects.equals(comment.getCreateId(), curUser.getContactId())) {
                            Date crtTime = DateTimeHelper.parse(comment.getCrtTime(), DateTimeHelper.YEAR_MONTH_DAY_HOUR_MINUTE_PATTERN);
                            logger.info("crtTime:{},now:{}", crtTime, now);
                            if (DateUtils.addMinutes(crtTime, 8).after(now)) {
                                if (comment.getType() == 0 || comment.getType() == 3) {
                                    comment.setCancelMsg(comment.getMsg());
                                }
                                if (comment.getType() == 1 || comment.getType() == 3) {
                                    comment.setCancelFileCode(comment.getFileCode());
                                }
                            }
                        }
                    } catch (Exception e) {
                        logger.info(e.getMessage(), e);
                    }
                    comment.setMsg("撤回了一条评论");
                    comment.setType(0);
                    comment.setFileCode(null);
                    comment.setFileName(null);
                }
            }
        }
    }
}
